//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import { observer } from 'mobx-react';
import { Button, Card, Input, List, message, Modal, Space } from "antd";
import type { NodeInfo } from "@/api/roadmap_content";
import { add_node, add_edge, NODE_TOPIC, LEARN_POLICY_NONE, EDGE_BEZIER, NODE_SUB_TOPIC } from "@/api/roadmap_content";
import { uniqId } from "@/utils/utils";
import { DeleteOutlined } from "@ant-design/icons";
import { useRoadmapStores } from "../store";
import { request } from "@/utils/request";


export interface BatchAddNodeModalProps {
    onClose: () => void;
}

interface NewSubTopicInfo {
    id: string;
    title: string;
    node?: NodeInfo;
}

interface NewTopicInfo {
    id: string;
    title: string;
    subTopicList: NewSubTopicInfo[];
    newSubTopicTitle: string;
    node?: NodeInfo;
}

const BatchAddNodeModal = (props: BatchAddNodeModalProps) => {
    const roadmapStore = useRoadmapStores();

    const [newTopicList, setNewTopicList] = useState<NewTopicInfo[]>([]);
    const [newTopicTitle, setNewTopicTitle] = useState("");
    const [inRun, setInRun] = useState(false);

    const addTopicNode = async (newTopicInfo: NewTopicInfo) => {
        let x: number | null = null;
        let y: number | null = null;
        for (const node of roadmapStore.nodeList) {
            if (x == null || y == null) {
                x = node.basic_info.node_position.x;
                y = node.basic_info.node_position.y + node.basic_info.node_size.h;
            } else {
                if (node.basic_info.node_position.x < x) {
                    x = node.basic_info.node_position.x;
                }
                if ((node.basic_info.node_position.y + node.basic_info.node_size.h) > y) {
                    y = node.basic_info.node_position.y + node.basic_info.node_size.h;
                }
            }
        }
        if (x == null) {
            x = 0;
        }
        if (y == null) {
            y = 10;
        }
        y += 50;
        const res = await request(add_node({
            session_id: roadmapStore.sessionId,
            roadmap_id: roadmapStore.roadmapId,
            basic_info: {
                node_type: NODE_TOPIC,
                node_size: {
                    w: 100,
                    h: 40,
                },
                node_position: {
                    x,
                    y,
                },
                node_data: {
                    TopicData: {
                        font_size: 16,
                        font_weight: 700,
                        font_color: "black",
                        title: newTopicInfo.title,
                        bg_color: "#fdff00",
                        content: "",
                        learn_policy: LEARN_POLICY_NONE,
                        link_list: [],
                    },
                },
            },
        }));
        await roadmapStore.onUpdateNode(res.node_id);
        newTopicInfo.node = roadmapStore.getNode(res.node_id);
    }

    const addSubTopicNode = async (subTopicList: NewSubTopicInfo[], baseX: number, baseY: number) => {
        let index = 0;
        for (const subTopic of subTopicList) {
            const res = await request(add_node({
                session_id: roadmapStore.sessionId,
                roadmap_id: roadmapStore.roadmapId,
                basic_info: {
                    node_type: NODE_SUB_TOPIC,
                    node_size: {
                        w: 100,
                        h: 40,
                    },
                    node_position: {
                        x: baseX + 500,
                        y: baseY + index * 60,
                    },
                    node_data: {
                        TopicData: {
                            font_size: 16,
                            font_weight: 700,
                            font_color: "black",
                            title: subTopic.title,
                            bg_color: "#ffe599",
                            content: "",
                            learn_policy: LEARN_POLICY_NONE,
                            link_list: [],
                        },
                    }
                },
            }));
            await roadmapStore.onUpdateNode(res.node_id);
            subTopic.node = roadmapStore.getNode(res.node_id);
            index++;
        }
    };

    const makeMainEdge = async (topicInfoList: NewTopicInfo[]) => {
        let lastNodeId = "";
        for (const topicInfo of topicInfoList) {
            if (lastNodeId == "") {
                lastNodeId = topicInfo.node?.node_id ?? "";
            } else {
                await request(add_edge({
                    session_id: roadmapStore.sessionId,
                    edge_key: {
                        from_node_id: lastNodeId,
                        from_handle_id: "b",
                        to_node_id: topicInfo.node?.node_id ?? "",
                        to_handle_id: "t",
                        roadmap_id: roadmapStore.roadmapId,
                    },
                    basic_info: {
                        edge_type: EDGE_BEZIER,
                        edge_color: "blue",
                        has_begin_arrow: false,
                        has_end_arrow: true,
                        edge_width: 4,
                    },
                }));
                lastNodeId = topicInfo.node?.node_id ?? "";
            }
        }
    };

    const makeSubEdge = async (topicInfo: NewTopicInfo) => {
        for (const subTopicInfo of topicInfo.subTopicList) {
            await request(add_edge({
                session_id: roadmapStore.sessionId,
                edge_key: {
                    from_node_id: topicInfo.node?.node_id ?? "",
                    from_handle_id: "r",
                    to_node_id: subTopicInfo.node?.node_id ?? "",
                    to_handle_id: "l",
                    roadmap_id: roadmapStore.roadmapId,
                },
                basic_info: {
                    edge_type: EDGE_BEZIER,
                    edge_color: "black",
                    has_begin_arrow: false,
                    has_end_arrow: false,
                    edge_width: 2,
                },
            }));
        }
    };

    const fitView = (topicInfoList: NewTopicInfo[]) => {
        const nodeList: { id: string }[] = [];
        for (const topicInfo of topicInfoList) {
            nodeList.push({ id: topicInfo.node?.node_id ?? "" });
            for (const subTopicInfo of topicInfo.subTopicList) {
                nodeList.push({ id: subTopicInfo.node?.node_id ?? "" })
            }
        }

        roadmapStore.flowInstance?.fitView({
            padding: 0.2,
            nodes: nodeList,
        });
    };

    const runBatchAdd = async () => {
        try {
            setInRun(true);
            const tmpList = newTopicList.slice();
            //创建节点
            for (const topicInfo of tmpList) {
                await addTopicNode(topicInfo);
                if (topicInfo.node == undefined) {
                    continue;
                }
                await addSubTopicNode(topicInfo.subTopicList, topicInfo.node.basic_info.node_position.x, topicInfo.node.basic_info.node_position.y);
            }
            //创建连接
            await makeMainEdge(tmpList);
            for (const topicInfo of tmpList) {
                await makeSubEdge(topicInfo);
            }
            await roadmapStore.loadEdgeList();
            fitView(tmpList);
            message.info("添加成功");
            props.onClose();
        } finally {
            setInRun(false);
        }
    };

    return (
        <Modal open title="批量添加" mask={false} bodyStyle={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll", padding: "10px 0px" }}
            okText="添加" okButtonProps={{ disabled: newTopicList.length == 0 || inRun }}
            cancelButtonProps={{ disabled: inRun }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                runBatchAdd();
            }}>
            {newTopicList.length > 0 && (
                <List rowKey="id" dataSource={newTopicList} pagination={false}
                    renderItem={topicItem => (
                        <List.Item>
                            <Card bordered={false} style={{ width: "100%" }} headStyle={{ backgroundColor: "#eee" }}
                                title={
                                    <Space>
                                        学习阶段:
                                        <Input style={{ width: "360px" }} value={topicItem.title} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = newTopicList.slice();
                                            const index = tmpList.findIndex(item => item.id == topicItem.id);
                                            if (index != -1) {
                                                tmpList[index].title = e.target.value.trim();
                                                setNewTopicList(tmpList);
                                            }
                                        }} />
                                    </Space>
                                } extra={
                                    <Button type="link" danger icon={<DeleteOutlined />} onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        const tmpList = newTopicList.filter(item => item.id != topicItem.id);
                                        setNewTopicList(tmpList);
                                    }}>删除</Button>
                                } bodyStyle={{ paddingLeft: "70px" }}>
                                {topicItem.subTopicList.length > 0 && (
                                    <List rowKey="id" dataSource={topicItem.subTopicList} pagination={false}
                                        renderItem={subTopicItem => (
                                            <List.Item extra={
                                                <Button type="link" danger icon={<DeleteOutlined />} onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    const tmpList = newTopicList.slice();
                                                    const i = tmpList.findIndex(item => item.id = topicItem.id);
                                                    if (i != -1) {
                                                        tmpList[i].subTopicList = tmpList[i].subTopicList.filter(item => item.id != subTopicItem.id);
                                                        setNewTopicList(tmpList);
                                                    }
                                                }}>删除</Button>
                                            }>
                                                <Space>
                                                    知识点:
                                                    <Input value={subTopicItem.title} onChange={e => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        const tmpList = newTopicList.slice();
                                                        const i = tmpList.findIndex(item => item.id = topicItem.id);
                                                        if (i != -1) {
                                                            const j = tmpList[i].subTopicList.findIndex(item => item.id == subTopicItem.id);
                                                            if (j != undefined && j != -1) {
                                                                tmpList[i].subTopicList[j].title = e.target.value.trim();
                                                                tmpList[i].subTopicList = tmpList[i].subTopicList.slice();
                                                            }
                                                        }
                                                        setNewTopicList(tmpList);
                                                    }} style={{ width: "310px" }} />
                                                </Space>
                                            </List.Item>
                                        )} />
                                )}
                                <Space>
                                    <Input value={topicItem.newSubTopicTitle} onChange={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        const tmpList = newTopicList.slice();
                                        const index = tmpList.findIndex(item => item.id == topicItem.id);
                                        if (index != -1) {
                                            tmpList[index].newSubTopicTitle = e.target.value.trim();
                                            setNewTopicList(tmpList);
                                        }
                                    }} style={{ width: "330px" }} placeholder="请输入知识点名称" />
                                    <Button type="default" disabled={topicItem.newSubTopicTitle == ""} onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        const tmpList = newTopicList.slice();
                                        const index = tmpList.findIndex(item => item.id == topicItem.id);
                                        if (index != -1) {
                                            tmpList[index].subTopicList.push({
                                                id: uniqId(),
                                                title: tmpList[index].newSubTopicTitle,
                                            });
                                            tmpList[index].subTopicList = tmpList[index].subTopicList.slice();
                                            tmpList[index].newSubTopicTitle = "";
                                            setNewTopicList(tmpList);
                                        }
                                    }}>增加知识点</Button>
                                </Space>
                            </Card>
                        </List.Item>
                    )} />
            )}
            <Space style={{ padding: "0px 10px" }}>
                <Input style={{ width: "380px" }} value={newTopicTitle} onChange={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    setNewTopicTitle(e.target.value);
                }} placeholder="请输入学习阶段名称" />
                <Button type="primary" disabled={newTopicTitle.trim() == ""}
                    onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        const tmpList = newTopicList.slice();
                        tmpList.push({
                            id: uniqId(),
                            title: newTopicTitle,
                            subTopicList: [],
                            newSubTopicTitle: "",
                        });
                        setNewTopicList(tmpList);
                        setNewTopicTitle("");
                    }}>增加学习阶段</Button>
            </Space>
        </Modal>
    )
};

export default observer(BatchAddNodeModal);